<template>
  <div class="icon-showcase-page" :class="{ 'dark-mode': darkMode }">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">图标组件</h1>
          <p class="page-subtitle">Element Plus 图标库展示，包含所有可用图标和使用示例</p>
        </div>
        <div class="header-right">
          <el-button-group>
            <el-button type="primary" @click="copyAllIcons">
              <el-icon><DocumentCopy /></el-icon>
              复制所有
            </el-button>
            <el-button @click="exportIconList">
              <el-icon><Download /></el-icon>
              导出列表
            </el-button>
            <el-button @click="toggleDarkMode" :type="darkMode ? 'warning' : 'info'">
              <el-icon><component :is="darkMode ? 'Sunny' : 'Moon'" /></el-icon>
              {{ darkMode ? '日间' : '夜间' }}模式
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索图标名称..."
              :prefix-icon="Search"
              clearable
              @input="filterIcons"
            />
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="selectedCategory"
              placeholder="选择分类"
              clearable
              @change="filterIcons"
            >
              <el-option
                v-for="category in categories"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-slider
              v-model="iconSize"
              :min="16"
              :max="48"
              :step="4"
              show-input
              :show-input-controls="false"
              @input="updateIconSize"
            />
            <span class="size-label">图标大小: {{ iconSize }}px</span>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 图标统计 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#409EFF"><Collection /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ totalIcons }}</div>
                <div class="stat-label">总图标数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#67C23A"><Filter /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ filteredIcons.length }}</div>
                <div class="stat-label">筛选结果</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#E6A23C"><FolderOpened /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ categories.length }}</div>
                <div class="stat-label">分类数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon size="32" color="#F56C6C"><Star /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ favoriteIcons.length }}</div>
                <div class="stat-label">收藏图标</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 收藏的图标 -->
    <div v-if="favoriteIcons.length > 0" class="favorite-section">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>收藏的图标</h3>
            <el-button @click="clearFavorites" type="danger" size="small">
              <el-icon><Delete /></el-icon>
              清空收藏
            </el-button>
          </div>
        </template>
        <div class="icon-grid">
          <div
            v-for="iconName in favoriteIcons"
            :key="iconName"
            class="icon-item favorite-item"
            @click="copyIconCode(iconName)"
          >
            <div class="icon-display">
              <el-icon :size="iconSize"><component :is="iconName" /></el-icon>
            </div>
            <div class="icon-name">{{ iconName }}</div>
            <div class="icon-actions">
              <el-button @click.stop="removeFavorite(iconName)" type="danger" size="small" text>
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图标网格 -->
    <div class="icons-section">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>所有图标 ({{ filteredIcons.length }})</h3>
            <div class="view-controls">
              <el-radio-group v-model="viewMode" @change="changeViewMode">
                <el-radio-button label="grid">网格</el-radio-button>
                <el-radio-button label="list">列表</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>
        
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="icon-grid">
          <div
            v-for="iconName in paginatedIcons"
            :key="iconName"
            class="icon-item"
            @click="copyIconCode(iconName)"
            @mouseenter="showTooltip($event, iconName)"
            @mouseleave="hideTooltip"
          >
            <div class="icon-display">
              <el-icon :size="iconSize"><component :is="iconName" /></el-icon>
            </div>
            <div class="icon-name">{{ iconName }}</div>
            <div class="icon-actions">
              <el-button 
                @click.stop="toggleFavorite(iconName)" 
                :type="isFavorite(iconName) ? 'warning' : 'info'" 
                size="small" 
                text
              >
                <el-icon><Star /></el-icon>
              </el-button>
              <el-button @click.stop="copyIconCode(iconName)" type="primary" size="small" text>
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="icon-list">
          <el-table :data="paginatedIconsTable" style="width: 100%">
            <el-table-column label="图标" width="80">
              <template #default="{ row }">
                <el-icon :size="24"><component :is="row.name" /></el-icon>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" />
            <el-table-column label="代码" width="300">
              <template #default="{ row }">
                <el-input 
                  :value="`<el-icon><${row.name} /></el-icon>`"
                  readonly
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button 
                  @click="toggleFavorite(row.name)" 
                  :type="isFavorite(row.name) ? 'warning' : 'info'" 
                  size="small"
                >
                  <el-icon><Star /></el-icon>
                </el-button>
                <el-button @click="copyIconCode(row.name)" type="primary" size="small">
                  <el-icon><DocumentCopy /></el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredIcons.length"
            :page-sizes="[20, 50, 100, 200]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 使用示例 -->
    <div class="usage-section">
      <el-card>
        <template #header>
          <h3>使用示例</h3>
        </template>
        <div class="usage-examples">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="example-block">
                <h4>基础用法</h4>
                <div class="example-demo">
                  <el-icon size="24"><House /></el-icon>
                  <el-icon size="24"><User /></el-icon>
                  <el-icon size="24"><Setting /></el-icon>
                </div>
                <div class="example-code">
                  <pre>&lt;el-icon&gt;&lt;House /&gt;&lt;/el-icon&gt;</pre>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="example-block">
                <h4>带颜色</h4>
                <div class="example-demo">
                  <el-icon size="24" color="#409EFF"><InfoFilled /></el-icon>
                  <el-icon size="24" color="#67C23A"><SuccessFilled /></el-icon>
                  <el-icon size="24" color="#E6A23C"><WarningFilled /></el-icon>
                  <el-icon size="24" color="#F56C6C"><CircleCloseFilled /></el-icon>
                </div>
                <div class="example-code">
                  <pre>&lt;el-icon color="#409EFF"&gt;&lt;InfoFilled /&gt;&lt;/el-icon&gt;</pre>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="example-block">
                <h4>不同尺寸</h4>
                <div class="example-demo">
                  <el-icon size="16"><Star /></el-icon>
                  <el-icon size="20"><Star /></el-icon>
                  <el-icon size="24"><Star /></el-icon>
                  <el-icon size="32"><Star /></el-icon>
                </div>
                <div class="example-code">
                  <pre>&lt;el-icon size="24"&gt;&lt;Star /&gt;&lt;/el-icon&gt;</pre>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 复制成功提示 -->
    <el-tooltip
      ref="copyTooltip"
      :visible="tooltipVisible"
      :content="tooltipContent"
      placement="top"
      virtual-triggering
      :virtual-ref="tooltipTrigger"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as ElementPlusIcons from '@element-plus/icons-vue'

// 获取所有Element Plus图标
const getAllIcons = () => {
  return Object.keys(ElementPlusIcons)
}

// 响应式数据
const darkMode = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const iconSize = ref(24)
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(50)
const favoriteIcons = ref(JSON.parse(localStorage.getItem('favoriteIcons') || '[]'))
const tooltipVisible = ref(false)
const tooltipContent = ref('')
const tooltipTrigger = ref()

// 所有图标
const allIcons = getAllIcons()
const totalIcons = allIcons.length

// 图标分类
const categories = [
  { label: '全部', value: '' },
  { label: '箭头类', value: 'arrow' },
  { label: '状态类', value: 'status' },
  { label: '操作类', value: 'action' },
  { label: '媒体类', value: 'media' },
  { label: '文件类', value: 'file' },
  { label: '用户类', value: 'user' },
  { label: '通用类', value: 'general' },
  { label: '导航类', value: 'nav' },
]

// 筛选后的图标
const filteredIcons = ref(allIcons)

// 分页后的图标
const paginatedIcons = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredIcons.value.slice(start, end)
})

// 表格形式的图标数据
const paginatedIconsTable = computed(() => {
  return paginatedIcons.value.map(name => ({ name }))
})

// 方法
const filterIcons = () => {
  let filtered = allIcons

  // 关键词筛选
  if (searchKeyword.value) {
    filtered = filtered.filter(icon => 
      icon.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(icon => {
      const iconLower = icon.toLowerCase()
      switch (selectedCategory.value) {
        case 'arrow':
          return iconLower.includes('arrow') || iconLower.includes('chevron') || 
                 iconLower.includes('caret') || iconLower.includes('right') || 
                 iconLower.includes('left') || iconLower.includes('up') || iconLower.includes('down')
        case 'status':
          return iconLower.includes('success') || iconLower.includes('error') || 
                 iconLower.includes('warning') || iconLower.includes('info') || 
                 iconLower.includes('check') || iconLower.includes('close')
        case 'action':
          return iconLower.includes('add') || iconLower.includes('delete') || 
                 iconLower.includes('edit') || iconLower.includes('save') || 
                 iconLower.includes('copy') || iconLower.includes('cut')
        case 'media':
          return iconLower.includes('play') || iconLower.includes('pause') || 
                 iconLower.includes('video') || iconLower.includes('music') || 
                 iconLower.includes('camera') || iconLower.includes('picture')
        case 'file':
          return iconLower.includes('file') || iconLower.includes('folder') || 
                 iconLower.includes('document') || iconLower.includes('download') || 
                 iconLower.includes('upload')
        case 'user':
          return iconLower.includes('user') || iconLower.includes('avatar') || 
                 iconLower.includes('people')
        case 'general':
          return iconLower.includes('home') || iconLower.includes('search') || 
                 iconLower.includes('setting') || iconLower.includes('help')
        case 'nav':
          return iconLower.includes('menu') || iconLower.includes('more') || 
                 iconLower.includes('grid') || iconLower.includes('list')
        default:
          return true
      }
    })
  }

  filteredIcons.value = filtered
  currentPage.value = 1
}

const updateIconSize = () => {
  // 实时更新图标大小
}

const copyIconCode = (iconName) => {
  const code = `<el-icon><${iconName} /></el-icon>`
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success(`已复制: ${iconName}`)
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

const toggleFavorite = (iconName) => {
  const index = favoriteIcons.value.indexOf(iconName)
  if (index > -1) {
    favoriteIcons.value.splice(index, 1)
    ElMessage.info(`已取消收藏: ${iconName}`)
  } else {
    favoriteIcons.value.push(iconName)
    ElMessage.success(`已收藏: ${iconName}`)
  }
  localStorage.setItem('favoriteIcons', JSON.stringify(favoriteIcons.value))
}

const isFavorite = (iconName) => {
  return favoriteIcons.value.includes(iconName)
}

const removeFavorite = (iconName) => {
  const index = favoriteIcons.value.indexOf(iconName)
  if (index > -1) {
    favoriteIcons.value.splice(index, 1)
    localStorage.setItem('favoriteIcons', JSON.stringify(favoriteIcons.value))
    ElMessage.info(`已取消收藏: ${iconName}`)
  }
}

const clearFavorites = () => {
  favoriteIcons.value = []
  localStorage.setItem('favoriteIcons', JSON.stringify([]))
  ElMessage.success('已清空收藏')
}

const copyAllIcons = () => {
  const iconList = allIcons.map(icon => `<el-icon><${icon} /></el-icon>`).join('\n')
  navigator.clipboard.writeText(iconList).then(() => {
    ElMessage.success(`已复制所有 ${allIcons.length} 个图标代码`)
  })
}

const exportIconList = () => {
  const iconData = {
    total: allIcons.length,
    categories: categories,
    icons: allIcons,
    favorites: favoriteIcons.value,
    exportTime: new Date().toISOString()
  }
  
  const dataStr = JSON.stringify(iconData, null, 2)
  const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr)
  
  const exportFileDefaultName = 'element-plus-icons.json'
  const linkElement = document.createElement('a')
  linkElement.setAttribute('href', dataUri)
  linkElement.setAttribute('download', exportFileDefaultName)
  linkElement.click()
  
  ElMessage.success('图标列表已导出')
}

const toggleDarkMode = () => {
  darkMode.value = !darkMode.value
  ElMessage.info(`已切换到${darkMode.value ? '夜间' : '日间'}模式`)
}

const changeViewMode = () => {
  ElMessage.info(`已切换到${viewMode.value === 'grid' ? '网格' : '列表'}视图`)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const showTooltip = (event, iconName) => {
  tooltipContent.value = `点击复制: ${iconName}`
  tooltipTrigger.value = event.target
  tooltipVisible.value = true
}

const hideTooltip = () => {
  tooltipVisible.value = false
}

// 生命周期
onMounted(() => {
  filterIcons()
})
</script>

<style scoped>
.icon-showcase-page {
  padding: 20px;
  min-height: 100vh;
  transition: all 0.3s ease;
}

.dark-mode {
  background-color: #1a1a1a;
  color: #e0e0e0;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.search-section {
  margin-bottom: 24px;
}

.size-label {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.favorite-section,
.icons-section,
.usage-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  position: relative;
}

.icon-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.favorite-item {
  border-color: #f56c6c;
  background: linear-gradient(135deg, #fff5f5 0%, #fff 100%);
}

.icon-display {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
}

.icon-name {
  font-size: 12px;
  color: #666;
  text-align: center;
  word-break: break-all;
  line-height: 1.4;
}

.icon-actions {
  display: flex;
  gap: 4px;
  margin-top: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.icon-item:hover .icon-actions {
  opacity: 1;
}

.icon-list {
  margin-top: 16px;
}

.pagination-section {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.usage-examples {
  margin-top: 16px;
}

.example-block {
  text-align: center;
}

.example-block h4 {
  font-size: 14px;
  color: #333;
  margin-bottom: 12px;
}

.example-demo {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.example-code {
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  border: 1px solid #e0e0e0;
}

.example-code pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 暗色主题适配 */
.dark-mode .stat-card {
  background-color: #2c2c2c;
  border-color: #404040;
}

.dark-mode .stat-number {
  color: #e0e0e0;
}

.dark-mode .icon-item {
  background-color: #2c2c2c;
  border-color: #404040;
  color: #e0e0e0;
}

.dark-mode .icon-item:hover {
  border-color: #409eff;
  background-color: #363636;
}

.dark-mode .example-demo {
  background: #2c2c2c;
}

.dark-mode .example-code {
  background: #2c2c2c;
  border-color: #404040;
  color: #e0e0e0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .icon-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .stats-section .el-row {
    --el-row-gutter: 12px;
  }
  
  .usage-examples .el-row {
    --el-row-gutter: 12px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.icon-item {
  animation: fadeIn 0.3s ease;
}

.icon-item:nth-child(even) {
  animation-delay: 0.1s;
}

.icon-item:nth-child(3n) {
  animation-delay: 0.2s;
}
</style>
